package dao

import (
	"context"
	"wxpay/internal/model"
	"wxpay/pkg/merrors"

	"github.com/nsqio/go-nsq"
	"gorm.io/gorm"
	"gorm.io/gorm/clause"
)

type ProfitReceiver interface {
	Save(ctx context.Context, tx *gorm.DB, pfs *model.ProfitReceiver) (err error)
}

type ProfitReceiverRepo struct {
	*gorm.DB
	producer *nsq.Producer
}

func NewProfitReceiverRepo(db *gorm.DB, p *nsq.Producer) *ProfitReceiverRepo {
	return &ProfitReceiverRepo{
		DB:       db,
		producer: p,
	}
}

// 保存分账方
func (p ProfitReceiverRepo) Save(_ context.Context, tx *gorm.DB, pfs *model.ProfitReceiver) (err error) {
	const op merrors.Op = "ProfitReceiverRepo.Ensure"
	if e := tx.Clauses(clause.OnConflict{
		Columns:   []clause.Column{{Name: "mch_id"}, {Name: "appid"}, {Name: "type"}, {Name: "account"}}, // key colume
		DoUpdates: clause.AssignmentColumns([]string{"update_time"}),                                     // column needed to be updated
	}).Create(pfs).Error; e != nil {
		return merrors.E(op, merrors.DBError, e, merrors.ErrInternal)
	}
	return nil
}
